<template>
  <div class="userManage">
    <h3>用户管理</h3>
    <button class="add_users" @click="addusers">添加用户</button>

    <!-- 提交表单 -->
    <div class="myform_all" v-if="ishow">
      <div class="getmyform">
        <button class="close_form" @click="closeForm">关闭</button>
        <form @submit.prevent="submitForm">
          <div>
            <label for="nickName">昵称:</label>
            <input type="text" id="nickName" v-model="getnickName" required>
          </div>
          <div>
            <label for="account">账号:</label>
            <input type="text" id="account" v-model="getaccount" required>
          </div>
          <div>
            <label for="password">密码:</label>
            <input type="password" id="password" v-model="getpassword" required>
          </div>
          <div>
            <label for="email">邮箱:</label>
            <input type="email" id="email" v-model="getemail" required>
          </div>
          <button type="submit" class="submit_btn">提交</button>
        </form>
        <p v-if="message" :class="messageType">{{ message }}</p>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="usersData" style="width: 100%" height="60vh">
      <el-table-column fixed prop="account" label="账号" width="150" />
      <el-table-column prop="nickName" label="昵称" width="160" />
      <el-table-column prop="sex" label="性别" width="100" />
      <el-table-column prop="age" label="年龄" width="100" />
      <el-table-column prop="createAt" label="创建时间" width="140" />
      <el-table-column label="头像" width="134">
        <template #default="scope">
          <img :src="scope.row.imgUrl" alt="头像" style="width: 40px; height: 40px; border-radius: 50%;" />
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="170" />
      <el-table-column prop="phone" label="手机号" width="200" />
      <el-table-column prop="id" label="id" width="200" />
      <el-table-column prop="operation" label="操作" width="100">
        <template #default="scope">
          <button @click="handleDelete(scope.row)" class="del_btn">删除</button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize" :total="total"
      layout="total, prev, pager, next" style="margin-top: 20px;" />
      
  </div>
</template>

<script lang="ts" setup>
import { userList } from '@/api/request'
import { deleuser } from '@/api/request'
import { register } from '@/api/request'
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, computed } from 'vue'

// 定义 usersData 为响应式引用
const usersData = ref([])

// 定义变量ishow来获取表单显隐
const ishow = ref(false)
// 定义四个变量来获取注册所需的数据
const getnickName = ref('')
const getaccount = ref('')
const getpassword = ref('')
const getemail = ref('')

const message = ref('')
const messageType = ref('')

const router = useRouter()

// 当前页码
const currentPage = ref(1)
// 每页记录数
const pageSize = ref(10)
// 总记录数
const total = ref(0)

// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 定义函数获取用户列表
const userListFn = async (page = 1, pageSize = 10) => {
  await userList({ page, pageSize }).then(content => {
    // console.log(content)
    const { code, total: totalCount, result } = content
    if (code === 200) {
      // 更新 total 的值
      total.value = totalCount

      // 更新 usersData 的值
      // console.log("total->", total.value);

      // 处理 createAt 时间戳
      const formattedResult = result.map(user => {
        const createAtTimestamp = user.createAt
        // console.log("createAtTimestamp (string):", createAtTimestamp); // 调试信息

        let formattedCreateAt = ''
        if (typeof createAtTimestamp === 'string' && !isNaN(Number(createAtTimestamp))) {
          const createAtNumber = Number(createAtTimestamp)
          // console.log("createAtTimestamp (number):", createAtNumber); // 调试信息
          formattedCreateAt = new Date(createAtNumber).toLocaleString()
        } else {
          console.error("Invalid createAt timestamp:", createAtTimestamp);
        }

        return {
          ...user,
          createAt: formattedCreateAt
        }
      })

      usersData.value = formattedResult
      // console.log("usersData.value", usersData.value)
    }
  })
}

// 初始化用户列表
userListFn(currentPage.value, pageSize.value)

// 处理分页组件的页码变化
const handlePageChange = (newPage: number) => {
  currentPage.value = newPage
  userListFn(newPage, pageSize.value)
}

interface User {
  account: string;
  nickName: string;
  sex: string;
  age: number;
  createAt: string;
  imgUrl: string;
  email: string;
  phone: string;
  role: boolean;
  id: number;
}

// 获取token
const mytoken = localStorage.getItem("TOKEN");

const handleDelete = async (row: User) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 用户点击确定，执行删除操作
      if (!row.role) {
        try {
          // console.log({ token: mytoken });

          // const response = await deleuser({ token: row.account });
          const response = await deleuser({ token: mytoken, data: row.id });

          // console.log("删除请求响应:", response);
          if (response.code === 200) {
            // console.log("删除成功");
            // 刷新用户列表
            userListFn(currentPage.value, pageSize.value);
          } else {
            console.log("删除失败", response.message || "未知错误");
            ElMessage({
              type: 'error',
              message: '删除失败',
            });
          }
        } catch (error) {
          // console.error("删除请求失败:", error);
          ElMessage({
            type: 'error',
            message: '删除请求失败',
          });
        }
      } else {
        // console.log("不能删除管理员");
        ElMessage({
          type: 'error',
          message: '不能删除管理员',
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};

// 唤醒添加用户界面
const addusers = async () => {
  ishow.value = true;
}

const submitForm = () => {
  // 处理表单提交逻辑
  // console.log('提交表单');
  // 提交表单数据到服务器
  submitFormData();
};

// 关闭表单
const closeForm = async () => {
  ishow.value = false;
  clearForm();
  router.go(0);
}

const clearForm = () => {
  getnickName.value = '';
  getaccount.value = '';
  getpassword.value = '';
  getemail.value = '';
}

const submitFormData = async () => {
  // 提交表单数据到服务器
  const data = {
    nickName: getnickName.value,
    account: getaccount.value,
    password: getpassword.value,
    email: getemail.value,
  };
  console.log(data);
  // 发送请求
  try {
    const response = await register(data);
    console.log(response);
    if (response.code == 200) {
      message.value = '提交成功';
      messageType.value = 'success';
      clearForm();
      ElMessage({
        type: 'success',
        message: '提交成功',
      })
    } else {
      message.value = '提交失败';
      messageType.value = 'error';
      ElMessage({
        type: 'error',
        message: '提交失败',
      })
    }
  } catch (error) {
    console.error('注册失败:', error);
  }
}
</script>

<style lang="scss" scoped>
.userManage {
  width: 100%;
  h3 {
    margin-bottom: 2vh;
    display: inline-flex;
  }

  .myform_all {
    display: block;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;

    .getmyform {
      width: 70vw;
      height: 70vh;
      background-color: rgb(255, 255, 255);
      position: relative;
      top: 15vh;
      left: 15vw;

      .close_form {
        position: relative;
        right: 0vw;
        margin-left: 65vw;
        width: 5vw;
        height: 4vh;
        cursor: pointer;

        &:hover {
          background-color: #ff3737;
          color: white;
        }
      }
    }
  }

  .add_users {
    z-index: 1000 !important;
    position: relative;
    display: inline-flex;
    margin-left: 50vw;
    height: 30px;
    line-height: 30px;
    background-color: white;
    cursor: pointer;

    &:hover {
      background-color: #e6e6e6;
    }
  }
}

.el-table--fit {
  background-color: rgb(0, 0, 0);
}

.del_btn {
  background-color: #ff3737;
  color: white;
  cursor: pointer;
}
</style>

<style scoped lang="scss">
.el-table {
  background-color: white !important;
}

.el-table__body-wrapper {
  background-color: white !important;
}

// 更改数据空白的背景色

.myform_all {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.getmyform {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.close_form {
  float: right;
  margin-bottom: 10px;
}

form div {
  margin-bottom: 10px;
}

form label {
  display: block;
  margin-bottom: 5px;
}

form input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

p.success {
  color: green;
}

p.error {
  color: red;
}

.submit_btn {
  width: 10vw;
  height: 4vh;
  position: relative;
  margin-left: 50vw;
  cursor: pointer;

  &:hover {
    background-color: #d6daff;
  }
}
</style>